#!/usr/bin/env python
#coding:utf-8

import os,sys
import xml.etree.ElementTree
import urlparse
import socket

#获取脚本文件的当前路径
def cur_file_dir():
    #获取脚本路径
    path = sys.path[0]
    #判断为脚本文件还是py2exe编译后的文件
    #如果是脚本文件，则返回的是脚本的目录
    #如果是py2exe编译后的文件，则返回的是编译后的文件路径
    if os.path.isdir(path):
        return path
    elif os.path.isfile(path):
        return os.path.dirname(path)

os.chdir(cur_file_dir())
tree = xml.etree.ElementTree.parse("../radiolist.xml")
root = tree.getroot()
radiotags = root.findall("radiotag")
InvalidUrls = []
isModified = False
for radiotag in radiotags:
    if radiotag.get("hidden")=="true":
        continue
    radios = radiotag.findall("radio")
    for radio in radios:
        sUrl = radio.get("url")
        url = urlparse.urlparse(sUrl)
        scheme = url.scheme
        hostname = url.hostname
        port = url.port
        if port==None:
            if scheme=="mms":
                port=1755
            elif scheme=="rtsp":
                port=554
            elif scheme=="http":
                port=80
            elif scheme=="ftp":
                port=21
            elif scheme=="https":
                port=443
            else:
                port=0
        s = None
        if scheme!="rtsp":
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        valid = False
        try:
            print "scanning %s:%d... " % (hostname,port),
            sys.stdout.flush()
            s.connect((hostname, port))
            print "ok."
            valid = True
            s.close()
        except Exception as e:
            print "failed!"
        if valid==False:
            InvalidUrls.append(sUrl)
            radio.set("hidden","true")
            isModified = True
        else:
            if radio.get("hidden")=="true":
                isModified = True
                radio.set("hidden","false")
if isModified==True:
    strOut = xml.etree.ElementTree.tostring(root,"utf-8")
    strOut = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + strOut
    f=open("../radiolist.xml","w")
    f.write(strOut)
    f.close()
    #tree.write("./radiolist.xml","utf-8")
if len(InvalidUrls)>0:
    print "\n----------the following url is invalid----------"
    for s in InvalidUrls:
        print s
print "scan finished."
        
